import React, { useState, useEffect } from 'react';
import {
  PlusSquareOutlined, ReloadOutlined,
  AppstoreOutlined,
  SelectOutlined
} from '@ant-design/icons';
import { Select, Button, Spin, Tabs } from 'antd';
import {
  openNotification_util, fetchsync_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS,
  addkey_for_mxdata
} from '../util/util.js'
var storage = window.localStorage;
const { Option } = Select;
import { use_xmkb_initcolmun } from './use_zbzx_config.js';
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';
import ResizableTable from '../newmes/Resize_table_hook.js';
import { useLatest } from 'ahooks';
import Sortable_new from '../newmes/sortable_new.js';
import 'moment/locale/zh-cn';

const Xm_kb_list = () => {
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [columnarr, setcolumnarr] = useState(use_xmkb_initcolmun)

  const [xmmc, setXmmc] = useState("")
  const [zbpl, setZbpl] = useState("")
  const xmmcRef = useLatest(xmmc)
  const zbplRef = useLatest(zbpl)

  const { setnowroute, collapsed } = useStore();


  useEffect(() => {
    querylist()
    storage[`Pc_kb_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_kb_list_${storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_kb_list_initsize_${storage.userid}`] ? setinitSize(storage[`Pc_kb_list_initsize_${storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转

  const querylist = async () => {
    setisloading(true)
    storage[`Pc_kb_list_${storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_kb_list_${storage.userid}`])) : setcolumnarr(columnarr)
    let rtdata = await fetchsync_util("/admin/zbzx/xmls_list", 'POST', { xmmc: xmmcRef.current, zbpl: zbplRef.current }, "json")
    // openNotification_util(rtdata.rtmessage)

    rtdata.resultdata.rtdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
      element.fbsj = element.fbsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.fbsj) : ""
      element.ybjzsj = element.ybjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.ybjzsj) : ""
      element.kbsj = element.kbsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.kbsj) : ""
      element.tbkssj = element.tbkssj ? convertISODateTimeToYYYYMMDDHHMMSS(element.tbkssj) : ""
      element.tbjzsj = element.tbjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(element.tbjzsj) : ""
      element.pbkssj = element.pbkssj ? convertISODateTimeToYYYYMMDDHHMMSS(element.pbkssj) : ""
      element.pbjssj = element.pbjssj ? convertISODateTimeToYYYYMMDDHHMMSS(element.pbjssj) : ""
    });
    setlistdata(dealnullorundenfined(rtdata.resultdata.rtdata))

    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
   * 手动查询
   */
  const handleQuery = async () => {
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_xm_kb_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey('xm_kb_form')
    setnowroute({ ...{ route: "/shipSRM/zbzx/xm_kb_form", title: "遴选_新增" } })
  }
  /**
   * 编辑
   */
  const handleEdit = async (data, type) => {
    storage.pre_xm_kb_item = JSON.stringify({ data, type })
    dropByCacheKey('xm_kb_form')
    setnowroute({ ...{ route: "/shipSRM/zbzx/xm_kb_form", title: "遴选_" + `${type == "edit" ? "编辑" : "查看"}` } })
  }

  const handleKb = async (data) => {
    // console.log(data.pbkssj, data.pbjssj);
    if (data.zbxs == '投标' && data.xmzt == '待竞价') {
      storage.pre_xm_kb_item = JSON.stringify({ data })
      dropByCacheKey('xm_kb_form')
      setnowroute({ ...{ route: "/shipSRM/zbzx/xm_kb_form", title: "遴选_淘汰" } })
    } else {
      openNotification_util("该项目未处于待竞价状态，无法进行淘汰设置")
    }
  }

  const TabPaneItem = (title, listdata, columnarr, key) => {
    return <Tabs.TabPane tab={<span>{title} <span style={{
      display: 'inline-block', padding: '0 6px', fontSize: '12px', lineHeight: '14px', backgroundColor: '#a91f24',
      color: 'white', borderRadius: '8px', marginLeft: '4px'
    }}>{listdata.length}</span></span>}
      key={key}>
      {isloading ?
        (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
          <Spin /></div>)
        :
        (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
          width={collapsed ? "94%" : "84%"}
          storageName={`Pc_kb_list_${storage.userid}`}
          czWidth={120}
          calcolor={(text) => {
            var color = "black"
            if (text == '驳回') {
              color = '#eb3617'
            }
            else if (text == '待审核') {
              color = '#3882f1'
            }
            else if (text == '审核通过') {
              color = '#1ee162'
            }
            return color
          }}
          rowCz={(record) => {
            var rowCz = {}
            console.log(record, "record");
            if (record.shzt == "审核通过" || record.shzt == "待审核") {
              rowCz = { showView: true }
            }
            else {
              rowCz = { showEdit: true, showView: true }
            }
            return rowCz
          }}
          czMaps={{
            showView: { cz: '查看', handle: "handleView" },
            showEdit: { cz: '编辑', handle: "handleEdit" },
          }}
          showCz={{ showEdit: true, showView: true, showDelete: true }}
          sfdoubleclick="false" ifhiddencchangeselecttype="true"
          selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
          // showCz={JSON.parse(storage.anpz).find(item => item.key == "xm")?.czAnpz}
          handleEdit={(data) => handleEdit(data, "edit")}
          handleView={(data) => handleEdit(data, "view")}
          scroll={{ x: 2000 }}
          defaultPageSize={10}
          bordered
          handleselectson={(selectedRows, selectedRowKeys) => {
            setselectedRows(selectedRows)
            setselectedRowKeys(selectedRowKeys)
          }}
        />)
      }
    </Tabs.TabPane>
  }


  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem",paddingRight:"1%"
    }}>

      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
          paddingLeft: "1vw",paddingRight:"1vw"
        }}>

          <div style={styleobj.linestyleflex}>
            <span style={{ fontSize: "0.8rem", fontWeight: "500" }}>工具栏</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            {/* <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>项目名称：</span>
            <Input style={{ width: "200px" }} value={xmmc} onChange={(e) => setXmmc(e.target.value)} />  &nbsp; &nbsp;
            <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>招标品类：</span>
            <Input style={{ width: "200px" }} value={zbpl} onChange={(e) => setZbpl(e.target.value)} />  &nbsp; &nbsp; */}
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷 新</Button>
            {/* &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { setXmmc(""); setZbpl("") }}>
              <ReloadOutlined />重 置</Button> */}
            {/* &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showAdd && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>} */}
            {/* &nbsp;{JSON.parse(storage.anpz).find(item => item.key == "xm")?.listAnpz?.showZb && <Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { selectedRows.length == 1 ? handleKb(selectedRows[0]) : openNotification_util("请选择要一条开标设置的项目！") }}>
              <SelectOutlined />淘 汰</Button>} */}
          </div>

          <div style={{ width: "100%", height: "0.3vw", backgroundColor: "#F1F1F1" }}></div>
          {ifshow && <Sortable_new tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_kb_list_${storage.userid}`} style={{ position: 'absolute', right: '2vw', top: '1.2rem', fontSize: "1.5rem" }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_kb_list_initsize_${storage.userid}`] = data; }}
          />}
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
              <Spin /></div>)
            :
            (<ResizableTable tabledata={listdata} tablecolnum={columnarr}
              width={collapsed ? "94%" : "84%"}
              storageName={`Pc_kb_list_${storage.userid}`}
              czWidth={120}
              rowCz={(record) => {
                var rowCz = {}
                console.log(record, "record");
                if (record.xmzt == "遴选") {
                  rowCz = { showEdit: true, }
                }
                else {
                  rowCz = { showView: true }
                }
                return rowCz
              }}
              czMaps={{
                showView: { cz: '查看', handle: "handleView" },
                showEdit: { cz: '遴选', handle: "handleEdit" },
              }}
              showCz={{ showEdit: true, showView: true, showDelete: true }}
              sfdoubleclick="false" ifhiddencchangeselecttype="true"
              selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
              // showCz={JSON.parse(storage.anpz).find(item => item.key == "xm")?.czAnpz}
              handleEdit={(data) => handleEdit(data, "edit")}
              handleView={(data) => handleEdit(data, "view")}
              scroll={{ x: 1700 }}
              defaultPageSize={10}
              bordered
              handleselectson={(selectedRows, selectedRowKeys) => {
                setselectedRows(selectedRows)
                setselectedRowKeys(selectedRowKeys)
              }}
            />)
          }
          {/* <Tabs defaultActiveKey="1" className='task-tabs' >
            {TabPaneItem("全部", addkey_for_mxdata(JSON.parse(JSON.stringify(listdata))), columnarr, "1")}
            {TabPaneItem("已", addkey_for_mxdata(listdata.filter(item => item.xmzt == "待发布")), columnarr, "2")}
            {TabPaneItem("标前询价", addkey_for_mxdata(listdata.filter(item => item.xmzt == "标前询价")), columnarr, "3")}
          </Tabs> */}

        </div>

      </div>
    </div>
  )
}


export default Xm_kb_list


var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1.5vw", paddingRight: "1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },


  kshcontainer: {
    width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
    color: "black"
  },
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem", marginTop: "0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}